/**   
 * @Title: ActionController.java 
 * @Package com.cms.zlinepay.payment.CMS.web.controllers 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author liuwei   
 * @date 2014-7-24 上午10:16:28 
 * @version V1.0   
 */
package com.cms.controllers;

import java.beans.PropertyEditorSupport;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cms.entity.Action;
import com.cms.entity.Role;
import com.cms.service.ActionService;
import com.cms.service.RoleService;
import com.cms.support.Result;

/**
 * @ClassName: ActionController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author zhangp
 * @date 2016年3月31日 下午2:45:24
 * 
 */
@Controller
public class ActionController {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(AdminController.class);
	@Autowired
	private RoleService roleService;
	@Autowired
	private ActionService actionService;

	/**
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Role.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				Integer id = Integer.parseInt(text);
				setValue(roleService.getRole(id));
			}
		});
	}

	/**
	 * @Title: loadRoles
	 * @Description: TODO(类方法所有进入的都会自动调用)
	 * @param model
	 *            void
	 * @throws
	 */
	@ModelAttribute
	public void loadRoles(Model model) {
		try {
			model.addAttribute("roles", roleService.listRoles());
			Set<Action> actions = actionService.getActionByUsername("admin")
					.getChildren();
			model.addAttribute("actions", actions);
			String json = "[{\"text\": \"根节点\",\"id\":\"1\",\"nodes\": [";
			for (Action action : actions) {
				json += "{\"text\": \"" + action.getTitle() + "\",\"id\":\""
						+ action.getId() + "\",\"nodes\": [";
				for (Action action2 : action.getChildren()) {
					json += "{\"text\": \"" + action2.getTitle()
							+ "\",\"id\":\"" + action2.getId() + "\"},";
				}
				json = json.substring(0, json.length() - 1);
				json += "]},";
			}
			json = json.substring(0, json.length() - 1);
			json += "]}]";
			model.addAttribute("actionJson", json);
		} catch (Exception e) {
			LOGGER.error(e.toString());
		}
	}

	/**
	 * @Title: index
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @return String
	 * @throws
	 */
	@RequestMapping("/action")
	public String index(Model model) {
		return "action/index";
	}

	/**
	 * @Title: list
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param request
	 * @param title
	 * @param iDisplayLength
	 * @param iDisplayStart
	 * @param sEcho
	 * @param model
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/action/list")
	public Object list(HttpServletRequest request, String title,
			Integer iDisplayLength, Integer iDisplayStart, Integer sEcho,
			Model model) {
		try {
			Long totalCount = actionService.getCount(title);
			List<Action> list = actionService.listDateActions(title,
					iDisplayStart, iDisplayLength);
			JSONObject getObj = new JSONObject();
			getObj.put("sEcho", sEcho);// 不知道这个值有什么用,有知道的请告知一下
			getObj.put("iTotalRecords", totalCount);// 实际的行数
			getObj.put("iTotalDisplayRecords", totalCount);// 显示的行数,这个要和上面写的一样
			getObj.put("aaData", list);// 要以JSON格式返回
			return getObj;
		} catch (Exception e) {
			LOGGER.error(e.toString());
			return null;
		}
	}

	/**
	 * @Title: add
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "action/add", method = RequestMethod.GET)
	public String add(Model model) {
		Action ac = new Action();
		model.addAttribute("action", ac);
		return "action/add";
	}

	/**
	 * @Title: doAdd
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param action
	 * @param parentId
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "action/add", method = RequestMethod.POST)
	public Object doAdd(Model model, @Valid Action action,
			@RequestParam Integer parentId) {
		try {
			Action a = actionService.loadAction(parentId);
			Action ac = new Action();
			ac.setId(action.getId());
			ac.setTitle(action.getTitle());
			ac.setUrl(action.getUrl());
			ac.setParent(a);
			actionService.saveAction(ac);
			return new Result();
		} catch (NumberFormatException e) {
			LOGGER.error(e.toString());
			return new Result(false, "系统异常");
		}
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param id
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "action/modify", method = RequestMethod.GET)
	public String modify(Model model, @RequestParam Integer id) {
		Action action = actionService.getAction(id);
		model.addAttribute("action", action);
		return "action/modify";
	}

	/**
	 * @Title: modify
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param action
	 * @param parentId
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "action/modify", method = RequestMethod.POST)
	public Object modify(Model model, @Valid Action action,
			@RequestParam Integer parentId) {
		try {
			Action a = actionService.loadAction(parentId);
			action.setParent(a);
			actionService.updateAction(action);
			return new Result();
		} catch (Exception e) {
			LOGGER.error(e.toString());
			return new Result(false, "系统异常");
		}
	}

	/**
	 * @Title: delete
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param model
	 * @param id
	 * @return Object
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/action/delete")
	public Object delete(Model model, @RequestParam Integer id) {
		try {
			actionService.removeById(id);
			return new Result();
		} catch (Exception e) {
			LOGGER.error(e.toString());
			return new Result(false, "系统异常");
		}
	}
}
